﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AutoGear.BLL;
using ECommerce.DAL;
using Entity;
using System.Text;
using System.IO;

public partial class controls_wucquickInvoiceMultipleWithPrice : System.Web.UI.UserControl
{
    private ProductPurchaseOrder _order;
    public ProductPurchaseOrder orders
    {
        get
        {
            if (_order == null)
            {
                if (ORDERID != null)
                {
                    _order = new ProductPurchaseOrder(ORDERID);
                    AutoGearSessionManager.OrderNumber = null;
                }
            }
            return _order;
        }
    }

    private string orderId;
    public string ORDERID
    {
        get { return orderId; }
        set { orderId = value; }
    }
    private Int32 OrderID
    {
        get
        {
            try
            {
                if (_order.OrderId != 0)
                {
                    return _order.OrderId;
                }
                else
                {
                    return -1;
                }
            }
            catch
            {
                return -1;
            }
        }
    }
    private CustomCollection<TblProductPurchaseOrder_MultipleShippingInfo> _orders;

    public CustomCollection<TblProductPurchaseOrder_MultipleShippingInfo> Order
    {
        get
        {
            if (orders != null)
            {
                return TblProductPurchaseOrder_MultipleShippingInfo.GetTblProductPurchaseOrder_MultipleShippingInfoByOrderId(orders.OrderId);
            }
            return null;
        }
    }

    private CustomCollection<TblProductPurchaseOrderItems_ForMultipleShipping> currentItems;

    private TblProductPurchaseOrder_MultipleShippingInfo currentShipping;

    private TblProductPurchaseOrder _CurrentOrder;

    public TblProductPurchaseOrder CurrentOrder
    {
        get
        {
            if (_CurrentOrder == null)
            {
                _CurrentOrder = TblProductPurchaseOrder.GetTblProductPurchaseOrderByOrderId(OrderID);
            }
            return _CurrentOrder;

        }
    }

    private decimal subtotal = 0;
    private decimal grandTotal = 0;
    private decimal shipcost = 0;

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            if (Order == null)
            {

            }
            else
            {
                BindOrders();
            }
        }
    }

    private void BindOrders()
    {
        //if (CurrentOrder.GIftCardMessage.Length > 0)
        //{
        //    trSubTotal.Visible = false;
        //    trSubTotal.Style.Add("display", "none");
        //}
        Session["subtotal"] = null;
        TblCreditCard card = TblCreditCard.GetTblCreditCardByCardId(CurrentOrder.CreditCardId); ;

        //lblGrandTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(CurrentOrder.OrderPrice + CurrentOrder.ShippingCost + CurrentOrder.TaxAmount);
        lblCouponDiscount.Text = "-" + ECommerce.Library.ECommerce.Utility.FormatPriceText(CurrentOrder.CouponDiscount);
        lblTax.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(CurrentOrder.TaxAmount);
        lblShippingHandling.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(CurrentOrder.ShippingCost);
        if (card != null)
        {
            if (CurrentOrder.PaymentByCreditCard > 0)
                lblCreditCard.Text = String.Format("{0:C}", CurrentOrder.PaymentByCreditCard) + "has been deducted from " + card.CardType + " ending in " + SiteUtility.HideCharacter(card.CardNumber, '*', card.CardNumber.Length - 4, true);
            else
                trCreaditCard.Style.Add("display", "none");
        }

        CustomCollection<TblProductPurchaseOrder_MultipleShippingInfo> shippings = TblProductPurchaseOrder_MultipleShippingInfo.GetTblProductPurchaseOrder_MultipleShippingInfoByOrderId(OrderID);
        repOrderShippngs.DataSource = shippings;
        repOrderShippngs.DataBind();

        if (CurrentOrder.Substitute.Length > 5)
        {
            lblSubstitute.Text = CurrentOrder.Substitute;
            lblSubstitute.Visible = false;
        }
       
      
        //if (!String.IsNullOrEmpty(CurrentOrder.GIftCardMessage))
        //{
        //    trSubTotal.Visible = false;
        //    trTotal.Visible = false;
        //}
        StringBuilder SB = new StringBuilder();
        StringWriter SW = new StringWriter(SB);
        HtmlTextWriter htmlTW = new HtmlTextWriter(SW);
        quickInvoice.RenderControl(htmlTW);
        string dataHTML = SB.ToString();
        StringReader reader = new StringReader(dataHTML);
      //  CreatePDFCrowdPDF(dataHTML);
        lblGrandTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(Convert.ToDecimal(Session["subtotal"]) + Convert.ToDecimal(lblShippingHandling.Text.Substring(1)) + Convert.ToDecimal(lblTax.Text.Substring(1)) - Convert.ToDecimal(lblCouponDiscount.Text.Substring(2)));
    }
    private void CreatePDFCrowdPDF(string htmlContent)
    {
        System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
        try
        {
            // create an API client instance
            pdfcrowd.Client client = new pdfcrowd.Client("polana", "2563aec6de3d0058353e599c653084cc");

            // convert a web page and write the generated PDF to a memory stream
            MemoryStream mStream = new MemoryStream();
            client.convertHtml(htmlContent, mStream);
            FileStream outStream = File.OpenWrite(Request.PhysicalApplicationPath + "pdf\\" + "" + orderId + ".pdf");
            mStream.WriteTo(outStream);
            outStream.Flush();
            outStream.Close();

        }
        catch (pdfcrowd.Error why)
        {
            Response.Write(why.ToString());
        }

    }
    protected void repOrderShippngs_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        currentShipping = e.Item.DataItem as TblProductPurchaseOrder_MultipleShippingInfo;
        if (currentShipping != null)
        {
            Literal litBillingAddressLine1 = (Literal)e.Item.FindControl("litBillingAddressLine1");
            litBillingAddressLine1.Text = CurrentOrder.BillingAddressLine1;
            Literal litBillingAddressLine2 = (Literal)e.Item.FindControl("litBillingAddressLine2");
            litBillingAddressLine2.Text = CurrentOrder.BillingAddressLine2;
            Literal litBillingAddressState = (Literal)e.Item.FindControl("litBillingAddressState");
            litBillingAddressState.Text = CurrentOrder.BillingAddressState;
            Literal litBillingCity = (Literal)e.Item.FindControl("litBillingCity");
            litBillingCity.Text = CurrentOrder.BillingCity;
            Literal litBillingEmailAddress = (Literal)e.Item.FindControl("litBillingEmailAddress");
            litBillingEmailAddress.Text = CurrentOrder.BillingEmailAddress;
            Literal litBillingFirstName = (Literal)e.Item.FindControl("litBillingFirstName");
            litBillingFirstName.Text = CurrentOrder.BillingFirstName;
            Literal litBillingLastName = (Literal)e.Item.FindControl("litBillingLastName");
            litBillingLastName.Text = CurrentOrder.BillingLastName;
            Literal litBillingTelephoneNumber = (Literal)e.Item.FindControl("litBillingTelephoneNumber");
            if (CurrentOrder.BillingTelephoneNumber.Length > 3)
                litBillingTelephoneNumber.Text = "Primary Phone: " + CurrentOrder.BillingTelephoneNumber;
            Literal litBillingTelephoneNumber2 = (Literal)e.Item.FindControl("litBillingTelephoneNumber2");
            if (CurrentOrder.BillingTelephoneNumber2.Length > 3)
                litBillingTelephoneNumber2.Text = "Secondary Phone: " + CurrentOrder.BillingTelephoneNumber2;
            Literal litBillingZipCode = (Literal)e.Item.FindControl("litBillingZipCode");
            litBillingZipCode.Text = CurrentOrder.BillingZipCode;
            Label lblDate = (Label)e.Item.FindControl("lblDate");
            lblDate.Text = CurrentOrder.CreateDate.ToShortDateString();

            Label lblRequestDeliveryDate = (Label)e.Item.FindControl("lblRequestDeliveryDate");
            lblRequestDeliveryDate.Text = currentShipping.RequestDate.ToShortDateString();

            Literal ltlCustomer = (Literal)e.Item.FindControl("ltlCustomer");
            TblUserOrder customer = TblUserOrderExtended.GetTblUserOrderByOrderId(CurrentOrder.OrderId);
            if (customer != null)
                ltlCustomer.Text = customer.UserId.ToString();

            Literal ltlSalesPerson = (Literal)e.Item.FindControl("ltlSalesPerson");
            if (CurrentOrder.SPId > 0)
                ltlSalesPerson.Text = CurrentOrder.SPId.ToString();

            Label lblShipmentStatus = (Label)e.Item.FindControl("lblShipmentStatus");
            string Shippingmethod = string.Empty;
            if (currentShipping.ShippingMethod == "1")
            {
                Shippingmethod = "Ground";
            }
            else if (currentShipping.ShippingMethod == "2")
            {
                Shippingmethod = "3 Day Select";
            }
            else if (currentShipping.ShippingMethod == "3")
            {
                Shippingmethod = "2nd Day Air";
            }
            else if (currentShipping.ShippingMethod == "4")
            {
                Shippingmethod = "Next Day Air";
            }
            lblShipmentStatus.Text = Shippingmethod;
            Label lblOrderNo = (Label)e.Item.FindControl("lblOrderNo");
            if (Session["count"] != null)
            {
                Session["count"] = Convert.ToInt32(Session["count"]) - 1;
                lblOrderNo.Text = CurrentOrder.OrderCode + Session["count"];

            }

            currentItems = TblProductPurchaseOrderItems_ForMultipleShipping.GetTblProductPurchaseOrderItems_ByMultipleShippingInfoId(currentShipping.ProductPurchaseOrder_MultipleShippingInfoId);

            if (currentItems != null)
            {
                subtotal = 0;
                Repeater rptProduct = e.Item.FindControl("rptProduct") as Repeater;
                rptProduct.DataSource = currentItems;
                rptProduct.DataBind();
                grandTotal += subtotal;
                Session["subtotal"] =Convert.ToDecimal(Session["subtotal"])+subtotal;
            }
            Label lblGiftCardMsg = (Label)e.Item.FindControl("lblGiftCardMsg");
            Label lblComments = (Label)e.Item.FindControl("lblComments");
            if (!String.IsNullOrEmpty(CurrentOrder.SpecialInstruction))
            {
                lblComments.Visible = true;
                lblComments.Text = "<b>Comments</b> :  " + CurrentOrder.SpecialInstruction;
                lblComments.Style.Add("height", "250px");
            }
            if (currentShipping.GIftCardMessage.Length > 1)
            {
                lblGiftCardMsg.Text = "<b>Gift Message :</b> " + currentShipping.GIftCardMessage;
                lblGiftCardMsg.Visible = true;
                lblGiftCardMsg.Style.Add("display", "block");
            }

        }
    }

    protected void rptProduct_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            //if (CurrentOrder.GIftCardMessage.Length > 0)
            //{
            //    Literal ltlItemNumber = (Literal)e.Item.FindControl("ltlItemNumber");
            //    ltlItemNumber.Visible = false;
            //    Literal ltlPrice = (Literal)e.Item.FindControl("ltlPrice");
            //    ltlPrice.Visible = false;
            //    Literal ltlTotal = (Literal)e.Item.FindControl("ltlTotal");
            //    ltlTotal.Visible = false;
            //}
        }

        else if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            TblProductPurchaseOrderItems_ForMultipleShipping cartItem = e.Item.DataItem as TblProductPurchaseOrderItems_ForMultipleShipping;
            TblProductPurchaseOrder_MultipleShippingInfo shipinfo = TblProductPurchaseOrder_MultipleShippingInfo.GetTblProductPurchaseOrder_MultipleShippingInfoByProductPurchaseOrder_MultipleShippingInfoId(Convert.ToInt32(cartItem.ProductPurchaseOrder_MultipleShippingInfoId));
            if (cartItem != null)
            {
                Product product = Product.Load(cartItem.ProductId);
                HyperLink hlkItem = (HyperLink)e.Item.FindControl("hlkItem");
                hlkItem.NavigateUrl = product.ProductUrl;
                if (product.ProductName != null)
                {
                    hlkItem.Text = product.ProductName;
                    hlkItem.Style.Add("text-decoration", "none");
                }
                else
                {
                    hlkItem.Text = "Name Deleted";
                    hlkItem.Style.Add("text-decoration", "none");
                }

                Label lblItemNumber = (Label)e.Item.FindControl("lblItemNumber");
                if (product.ItemNumber != null)
                    lblItemNumber.Text = product.ItemNumber;
                else
                    lblItemNumber.Text = "Deleted";

                Label lblItemPrice = (Label)e.Item.FindControl("lblItemPrice");
                lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.Price);

                Label lblQuantity = (Label)e.Item.FindControl("lblQuantity");
                lblQuantity.Text = cartItem.Quantity.ToString();

                Label lblItemTotal = (Label)e.Item.FindControl("lblItemTotal");
                decimal total = cartItem.Quantity * cartItem.Price;
                subtotal += total;
                lblItemTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(total);
                shipcost = shipinfo.ShippingCost;

                //if (CurrentOrder.GIftCardMessage.Length > 0)
                //{
                //    lblItemNumber.Visible = false;
                //    lblItemPrice.Visible = false;
                //    lblItemPrice.Visible = false;
                //    lblItemTotal.Visible = false;
                //}
            }
        }
        else if (e.Item.ItemType == ListItemType.Footer)
        {
            Literal ltlSubTotal = (Literal)e.Item.FindControl("ltlSubTotal");
            Label lblSubTotal = (Label)e.Item.FindControl("lblSubTotal");
            lblSubTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(subtotal);
            //if (CurrentOrder.GIftCardMessage.Length > 0)
            //{  
            //    ltlSubTotal.Visible = false;
            //    lblSubTotal.Visible = false;
            //}
        }
    }
}